import React, { useState, useEffect } from 'react';

import {
  deviceManagerListApi,
  deviceManagerBindGatewayApi,
  type DeviceItem,
} from '@/api/deviceManagerApi';
import { ProductNodeType, DeviceListStatus, getEnumItem } from '@/constants';

/**
 * 绑定网关模态框组件属性
 */
interface BindGatewayModalProps {
  /** 模态框显示状态 */
  visible: boolean;
  /** 选中的设备列表 */
  selectedDevices: DeviceItem[];
  /** 取消回调 */
  onCancel: () => void;
  /** 成功回调 */
  onSuccess: () => void;
}

/**
 * 绑定网关弹窗组件
 */
const BindGatewayModal: React.FC<BindGatewayModalProps> = ({
  visible,
  selectedDevices,
  onCancel,
  onSuccess,
}) => {
  const [gatewayList, setGatewayList] = useState<DeviceItem[]>([]);
  const [selectedGateway, setSelectedGateway] = useState<DeviceItem | null>(null);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取网关设备列表
  const fetchGatewayList = async (current = 1, pageSize = 10, deviceCode?: string) => {
    setLoading(true);
    try {
      const params: any = {
        nodeType: ProductNodeType.GATEWAY.value,
        pageSize,
        current,
      };

      // 如果有搜索条件，添加deviceCode参数
      if (deviceCode) {
        params.deviceCode = deviceCode;
      }

      const res = await deviceManagerListApi(params);

      if (res.success && res.data) {
        // 处理API返回的数据结构
        const records = Array.isArray(res.data) ? res.data : (res.data as any).records || [];
        const total = Array.isArray(res.data) ? res.data.length : (res.data as any).total || 0;

        setGatewayList(records);
        setPagination({
          current,
          pageSize,
          total,
        });
      } else {
        setGatewayList([]);
        setPagination({
          current: 1,
          pageSize: 10,
          total: 0,
        });
      }
    } catch (error) {
      console.error('获取网关列表失败:', error);
      setGatewayList([]);
      setPagination({
        current: 1,
        pageSize: 10,
        total: 0,
      });
    } finally {
      setLoading(false);
    }
  };

  // 搜索网关
  const handleSearch = () => {
    // 重置到第一页并搜索
    fetchGatewayList(1, 10, searchText.trim() || undefined);
  };

  // 分页变化处理
  const handleTableChange = (page: number, pageSize: number) => {
    fetchGatewayList(page, pageSize, searchText.trim() || undefined);
  };

  // 确认绑定
  const handleConfirm = async () => {
    if (!selectedGateway) {
      window.$message.warning('请选择要绑定的网关');
      return;
    }

    setConfirmLoading(true);
    try {
      const childDeviceIds = selectedDevices.map(device => String(device.id));

      const res = await deviceManagerBindGatewayApi({
        childDeviceIds,
        gatewayCode: selectedGateway.code,
        gatewayPk: selectedGateway.productCode || '', // 使用productCode作为gatewayPk
      });

      if (res.success) {
        window.$message.success('绑定网关成功');
        onSuccess();
        handleCancel();
      } else {
        window.$message.error(res.message || '绑定网关失败');
      }
    } catch (error) {
      console.error('绑定网关失败:', error);
      window.$message.error('绑定网关失败，请重试');
    } finally {
      setConfirmLoading(false);
    }
  };

  // 取消操作
  const handleCancel = () => {
    setSelectedGateway(null);
    setSearchText('');
    setGatewayList([]);
    setPagination({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    onCancel();
  };

  // 弹窗打开时获取网关列表
  useEffect(() => {
    if (visible) {
      fetchGatewayList(1, 10);
    }
  }, [visible]);

  // 表格列定义
  const columns = [
    {
      title: '设备code',
      dataIndex: 'code',
      key: 'code',
      width: 200,
    },
    {
      title: '所属产品',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: number) => {
        const activeItem = getEnumItem(DeviceListStatus, String(status));
        return activeItem?.label || '未知';
      },
    },
  ];

  return (
    <AModal
      title="绑定网关"
      open={visible}
      onCancel={handleCancel}
      onOk={handleConfirm}
      okText="确认"
      cancelText="取消"
      width={800}
      confirmLoading={confirmLoading}
    >
      <ARow className="mb-4" gutter={16}>
        <ACol span={13}></ACol>
        <ACol span={8}>
          <AInput
            placeholder="请输入设备名称或id查询"
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            onPressEnter={handleSearch}
          />
        </ACol>
        <ACol span={2}>
          <AButton type="primary" onClick={handleSearch} loading={loading}>
            搜索
          </AButton>
        </ACol>
      </ARow>

      <ATable
        dataSource={gatewayList}
        rowKey="id"
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: false,
          showQuickJumper: false,
          showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
          onChange: handleTableChange,
        }}
        rowSelection={{
          type: 'radio',
          selectedRowKeys: selectedGateway ? [selectedGateway.id!] : [],
          onChange: (_, selectedRows) => {
            setSelectedGateway((selectedRows[0] as DeviceItem) || null);
          },
        }}
        columns={columns}
        scroll={{ y: 400 }}
      />
    </AModal>
  );
};

export default BindGatewayModal;
